<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############


if(get('r')!=''){
    error_reporting(E_ALL);
    $params = $DATACRYPT->decrypt(str_replace(' ', '+', $_GET['r']));
    $url = $CONFIG->baseUrl.'/?'.$params;
    JFX::interpretUrlParams($url);
}




$username = $DB->escape(get('username'));

if($this->getConfig('allow-guests') && strtolower($username)=='guest'){
    $guest = true;
}else{
    $guest = false;
}

$password = get('password');
$lang = $DB->escape(get('lang'));
if($DB->countRows($CONFIG->dbprefix.'languages', "keyname = '{$lang}'")==0){
    $lang = $DB->oneValue($CONFIG->dbprefix.'languages', 'keyname', "is_default = 1");
}

$res->result = 'FAIL';
$res->conn = '';

if(!$guest && $DB->countRows($CONFIG->dbprefix.'iusers', "username = '{$username}'")==0){
    $res->reason = 'Invalid username';
    die(serialize($res));
}else{
    if(!$guest){
        $uData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}iusers WHERE username = '{$username}'");

        if($CRYPT->decrypt($uData['pass']) === $password){
            // successful login
            $rand = md5(rand(0, 999999));
            while($DB->countRows($CONFIG->dbprefix.'vms_connections', "conn = '{$rand}'")>0) $rand = md5(rand(0, 999999));
            $dbParams = array(
                'user_id' => $uData['id'],
                'start_tstamp' => time(),
                'end_tstamp' => time()+(60*(int) $this->getConfig('connection-timeout')),
                'lang' => $lang,
                'conn' => $rand
            );
            $DB->insert($CONFIG->dbprefix.'vms_connections', $dbParams);
        }else{
            // guests
            $rand = md5(rand(0, 999999));
            while($DB->countRows($CONFIG->dbprefix.'vms_connections', "conn = '{$rand}'")>0) $rand = md5(rand(0, 999999));
            $dbParams = array(
                'user_id' => 0,
                'start_tstamp' => time(),
                'end_tstamp' => time()+(60*(int) $this->getConfig('connection-timeout')),
                'lang' => $lang,
                'conn' => $rand
            );
            $DB->insert($CONFIG->dbprefix.'vms_connections', $dbParams);
        }
        $res->result = 'SUCCESS';
        $res->conn = $rand;
        die(serialize($res));
    }else{
        // wrong password
        $res->reason = 'Invalid password';
        die(serialize($res));
    }
}